<?php
/*
*安全告知登记
*/
namespace control;


class safetyRegistrationClass extends \control\adIndexClass
{
    private const page = 'safetyRegistration';
    private const table = 'safety_registration';
    private const title = '安全告知登记';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'          => [
                        'name'  => '姓名',
                        'width' => 150,
                    ],
                    'sex'          => [
                        'name'  => '性别',
                        'width' => 150,
                    ],
                    'idNum'         => [
                        'name'  => '证件号码',
                        'width' => 150,
                    ],
                    'leaveUnit'          => [
                        'name'  => '单位名称',
                        'width' => 150,
                    ],
                    'station'          => [
                        'name'  => '岗位',
                        'width' => 150,
                    ],
                    'visitDate'          => [
                        'name'  => '安全教育日期',
                        'width' => 150,
                    ],
                    'endVisitDate'          => [
                        'name'  => '安全教育到期时间',
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单位名称：" => text(["name" => "leaveUnit", 'class' => 'text', "value" => '']),
                    "姓名" => text(array("name" => "name")),
                    "证件号码"     => text(array("name" => "idNum")),
                ],
            ]
        ]);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "leaveUnit" => $this->post('leaveUnit'),
            "name" => $this->post('name'),
            "idNum" => $this->post('idNum'),
        );
        //全等查询数组
        $equal = array();
        $and = "";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "姓名：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    must . "性别：" => select(["name" => "sex", 'title' => '类型', 'option' => ['男','女'], 'class' => 'text', "value" => $info['sex']]),
                ],
                [
                    must . "证件号码：" => text(["name" => "idNum", 'class' => 'text', "value" => $info['idNum']]),
                    must . "单位名称：" => text(["name" => "leaveUnit", 'class' => 'text', "value" => $info['leaveUnit']]),
                ],
                [
                    must . "岗位：" => text(["name" => "station", 'class' => 'text', "value" => $info['station']]),
                    "安全教育日期：" => text(["name" => "visitDate", 'class' => 'text','laydate'=>[], "value" => $info['visitDate']]),
                ],
                [
                    "安全教育到期时间：" => text(["name" => "endVisitDate", 'class' => 'text','laydate'=>[], "value" => $info['endVisitDate']]),
                ],
                [
                    "<div class='small-title'>附件</div>" .
                    \control\fileUploadClass::addFileComponent($info['id'], '来访登记', self::page, self::page . 'EditForm')
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'idNum' => $this->post('idNum'),
            'leaveUnit' => $this->post('leaveUnit'),
            'station' => $this->post('station'),
            'visitDate' => $this->post('visitDate'),
            'endVisitDate' => $this->post('endVisitDate'),
            'updateTime' => $this->time
        ];
        $fileIdArr = $this->post('fileId');
        $annotation = [
            'name' => '姓名',
            'sex' => '性别',
            'idNum' => '证件号码',
            'leaveUnit' => '单位名称',
            'station' => '岗位',
            'visitDate' => '安全教育日期',
            'endVisitDate' => '安全教育到期时间',
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'idNum' => 'required',
            'leaveUnit' => 'required',
            'station' => 'required',
            'visitDate' => 'required',
            'endVisitDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];

            }
            //生成表单
            $fileCollection = \control\fileUploadClass::showFile($info['id'], '来访登记');
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "姓名" => $info['name'],
                        "性别" => $info['sex'],
                        "证件号码" => $info['idNum'],
                        "单位名称" => $info['leaveUnit'],
                    ),
                    array(
                        "岗位" => $info['station'],
                        "安全教育日期" => $info['visitDate'],
                        "安全教育到期时间" => $info['endVisitDate'],
                    ),
                ),
                '附件' => array(
                    array(
                        $fileCollection
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $word = false;
        $form = $power = '';
        switch ($act) {
            case 'drill':
                $act      = 'drill';
                $msg      = '再教育';
                $title    = '是否确认再教育，确认后将不可修改？';
                $function = 'drillEdit';
                $form     = 'listForm';
                $word     = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 再教育修改
     * @return false|string
     * @throws Exception
     */
    public function drillEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "drill")) {
            $json['warn'] = "你没有再教育的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                update(array("table" => self::table,"field"=>['visitDate'=>$this->date,'endVisitDate'=>date("Y-m-d h:i:s", strtotime("+180 days", strtotime($this->date)))], "where" => " id = '$id' "));
                //返回
                $warn = "再教育成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "培训了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "培训了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");

                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;

                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

